package org.soarsky.wealthchengdu.module.focus;

import java.util.List;

import org.soarsky.wealthchengdu.R;
import org.soarsky.wealthchengdu.appliction.MyAppliction;
import org.soarsky.wealthchengdu.db.DBtool;
import org.soarsky.wealthchengdu.entity.JsonResult;
import org.soarsky.wealthchengdu.entity.LogonResult;
import org.soarsky.wealthchengdu.entity.NewsContentData;
import org.soarsky.wealthchengdu.network.ParserResults;
import org.soarsky.wealthchengdu.util.Config;
import org.soarsky.wealthchengdu.view.ALLSendDialog;

import android.app.Activity;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * 滑动的界面适配器
 * 
 * @author huang
 * 
 */
public class ViewPagerAdapter extends PagerAdapter {
	public List<View> mListViews;// 添加的布局文件
	public static NewsContentData newscontentdata;

	private Activity activity;
	private static ParserResults service;

	/**
	 * content
	 */
	public ViewPagerAdapter(List<View> mListViews, Activity activity) {
		this.activity = activity;
		this.mListViews = mListViews;
		service = new ParserResults();
	}

	/**
	 * 刷新数据
	 */
	public void notifydataSetchanged() {
		this.notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		if (MyAppliction.ifcollect) {
			return MyAppliction.collectlistID.size();
		} else {
			return MyAppliction.list.size();
		}

	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {

		return arg0 == (arg1);
	}

	@Override
	public Object instantiateItem(View arg0, int position) {
		if (((ViewPager) arg0).getChildCount() == mListViews.size()) {
			((ViewPager) arg0).removeView(mListViews.get(position
					% mListViews.size()));
		}
		((ViewPager) arg0).addView(
				mListViews.get(position % mListViews.size()), 0);
		return mListViews.get(position % mListViews.size());
	}

	@Override
	public void destroyItem(View view, int position, Object arg2) {
		// ((ViewPager)
		// arg0).removeView(mListViews.get(arg1%mListViews.size()));
		// Log.e("destroy  position", position + "");
		// ((ViewPager) view).removeView(mListViews.get(position
		// % mListViews.size()));
	}

	/**
	 * 跳转到每个页面都要执行的方法
	 */
	@Override
	public void setPrimaryItem(View container, int position, Object object) {
		// //把这个position赋值到一个全局变量，通过这个就会知道滑动到哪个页面了
		// setPosition(position);
		// //保证每条新闻都只请求一次联网，执行过后就不在执行getNewsData方法了
		// if (positionValue[position] == false) {
		// //这个方法就是联网获取数据
		// getNewsData(categoryId, position);
		// if (Logs.IS_DEBUG) {
		// Logs.v("guo", "联网请求............."+itemPosttion);
		// }
		// positionValue[position] = true;

		// }
		ImageView focus_iv_three = (ImageView) mListViews.get(
				position % mListViews.size()).findViewById(R.id.focus_iv_three);
		WebView webview = (WebView) mListViews
				.get(position % mListViews.size()).findViewById(
						R.id.focus_webview);
		if (MyAppliction.ifcollect) {
			setwebview(webview, MyAppliction.collectlistID.get(position));
		} else {
			loadData(webview);
		}

		Cursor cusor = DBtool.getDBTool(activity).select(MyAppliction.ID);
		if (cusor.getCount() > 0) {
			focus_iv_three.setImageResource(R.drawable.focus_btn_three_up);
		}

	}

	private void loadData(final WebView webView) {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				getLogon();
				try {
					JsonResult<NewsContentData> result = service
							.getNewsContent(MyAppliction.ID);
					if (result == null)
						return false;
					if (result.isError()) {
						error(result);
						// 错误处理
						return false;
					} else {
						NewsContentData dataMsg = result.getData();
						if (dataMsg != null) {// 判断是否有数据
							newscontentdata = dataMsg;
							return true;
						}

					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
				}
				return false;
			}

			protected void onPostExecute(Boolean result) {
				// UI更新操作
				if (result) {
					setwebview(webView, newscontentdata);
				} else {

				}

			};
		}.execute();
	}

	// 必须先登录
	private void getLogon() {
		try {
			JsonResult<LogonResult> jsonResult = service.authLogon("张三");
			if (jsonResult != null) {
				if (jsonResult.isError()) {
					error(jsonResult);
				} else {// 登录成功
					System.out.println(jsonResult.getData().getUserId() + "==="
							+ jsonResult.getData().getNickName());
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.toString() + "===");
		}
	}

	private static void error(JsonResult<?> jsonResult) {
		System.out.println("错误码:" + jsonResult.getCode() + "===错误信息:"
				+ jsonResult.getMsg());
	}

	public void setwebview(WebView webview, NewsContentData newscontentdatato) {
		if (newscontentdata != null) {
			if (MyAppliction.mCn == 0) {
				if(MyAppliction.mChoose==4){
					webview.loadDataWithBaseURL(null, MyAppliction.video
							+ newscontentdatato.getContent()
							+ MyAppliction.htmlbottom, "text/html", "utf-8", null);
					webview.setWebChromeClient(new MyWebChromeClient());
				}
				webview.loadDataWithBaseURL(null, MyAppliction.htmlhead
						+ newscontentdatato.getContent()
						+ MyAppliction.htmlbottom, "text/html", "utf-8", null);
				webview.setWebChromeClient(new MyWebChromeClient());
				// webview.setWebViewClient(new WebViewClient()
				// {
				// @Override
				// public void onPageFinished(WebView view,String url)
				// {
				// ALLSendDialog.dimssdialog();
				// }
				// });
			} else {
				if(MyAppliction.mChoose==4){
					webview.loadDataWithBaseURL(null, MyAppliction.video
							+ newscontentdatato.getContent()
							+ MyAppliction.htmlbottom, "text/html", "utf-8", null);
					webview.setWebChromeClient(new MyWebChromeClient());
				}
				webview.loadDataWithBaseURL(null, MyAppliction.htmlhead
						+ newscontentdatato.getContentEn()
						+ MyAppliction.htmlbottom, "text/html", "utf-8", null);
				webview.setWebChromeClient(new MyWebChromeClient());
				// webview.setWebViewClient(new WebViewClient()
				// {
				// @Override
				// public void onPageFinished(WebView view,String url)
				// {
				// ALLSendDialog.dimssdialog();
				// }
				// });
			}
		} else {
			Toast.makeText(activity,
					Config.changeLanguage(MyAppliction.mChoose).getNodata(),
					Toast.LENGTH_LONG).show();
		}
	}

	class MyWebChromeClient extends WebChromeClient {
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			// TODO Auto-generated method stub
			// 查看加载进度
			Log.e("the load", "~~~~~~~~progress:" + newProgress); // //////////
			// 加载完毕
			if (newProgress == 100) {
				ALLSendDialog.dimssdialog();
			}
			super.onProgressChanged(view, newProgress);
		}

	}
}
